
<script setup>
import { reactive, ref, onMounted} from 'vue';
// 确保引入Element Plus的消息提示（如果用到）
import { ElMessage } from 'element-plus';
import {queryProductList,updateProductInfo,deleteProduct,insertProduct,activeList,activeCategoryList} from '@/apis/productAPI';
import { userStatusMap } from '@/utils/dict';
// 表格数据源必须是数组（每个元素对应一行）
const productList = ref([]);


// 搜索方法
const handleSearch = async() => {
  await fetchData();

}
const isEditDialogOpen = ref(false); // 控制对话框显示/隐藏
const currentProduct= reactive({
  id:'',
  productName:'',
  stock:'',
  status:'',
  price:''

});
const productForm=reactive({
  productName:'',
  price:'',
  status:1,
  stock:'',
  categoryId:'',
  supplierId:''
})
//添加弹窗
const isAddOpen=ref(false);
// 3. 页面加载时填充数据（模拟接口请求）





onMounted(async () => {
  fetchData();
});




// 4. 编辑功能
const openDialog = (product) => {
  Object.assign(currentProduct,product);
  isEditDialogOpen.value = true;
};

// 5. 保存编辑
const saveProduct = async() => {
  try{
     console.log("准备提交的商品数据:", currentProduct);
    await updateProductInfo(currentProduct);
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败");
  }finally{
    isEditDialogOpen.value=false;
  }

};
const deletePro=async(product)=>{
  try{
    const deleteId=product.id;
    await deleteProduct(deleteId);
    ElMessage.success("删除成功");
    fetchData();
  }catch{
    ElMessage.error("删除失败");
  }
}
const addProduct=async()=>{
  try{
    await insertProduct(productForm);
    ElMessage.success("添加成功");
  }catch{
    ElMessage.error("添加失败");
  }finally{
    isAddOpen.value=false
  }
}
// 分页相关变量
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};
const total=ref();
const params=ref({
  pageNo:'',
  pageSize:'',
  status:'',
}
)
const fetchData=async()=>{
  try{
    params.value.pageNo=currentPage;
    params.value.pageSize=pageSize.value;
    const {data}=await queryProductList(params.value);
    productList.value=data.records;
    total.value=data.total;

  }catch{
    ElMessage.error("加载失败");
  }

}
const AddDialog=()=>{
  isAddOpen.value=true;
  getActiveList();
  getActiveCategory();
}
//供应商和分类
const categoryList=ref([]);
const supplierList=ref([]);
const getActiveList=async()=>{
  try{
    const {data}=await activeList();
    supplierList.value=data;
  }catch{
    ElMessage.error("加载失败");
  }
}
const getActiveCategory=async()=>{
  try{
    const {data}=await activeCategoryList();
    categoryList.value=data;
  }catch{
    ElMessage.error("加载失败");
  }
}
</script>
<template>
  <div class="container">
    <div class="userList-header">
     <div class="search-box">
       <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
     </div>
     <el-button class="addBtn" type="primary" @click="AddDialog">添加</el-button>
    </div>
    <!-- 表格必须绑定数组数据 -->
    <div class="table_container">
    <el-table :data="productList"  border style="width: 900px; margin-top: 20px; min-height: 100%;">
      <el-table-column label="ID" prop="id" min-width="80%" width="80%">
         <template #default="scope">
          <span class="title-link"  @click="toDetail(scope.row)">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="productName"  />
      <!-- <el-table-column label="供应商" prop="supplierName"  min-width="80%" /> -->
       <el-table-column label="库存" prop="stock"  min-width="80%"  type="number"/>
      <el-table-column label="价格" prop="price"  min-width="80%" />
      <el-table-column label="状态" prop="status"  min-width="80%"  type="number">
        <template #default="scope">
         <el-tag type="warning" v-if=" scope.row.status===0 ">{{ userStatusMap[scope.row?.status] ?? '未知' }}</el-tag>
         <el-tag type="success" v-if=" scope.row.status===1 ">{{ userStatusMap[scope.row?.status] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"  min-width="100%">
        <template #default="scope">  <!-- 必须用template包裹按钮 -->
          <div class="btn">
            <el-button @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deletePro(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        page-sizes=10
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑产品" >
      <el-form :model="currentProduct" label-width="150px" style="width: 600px">
        <el-form-item label="ID">
          <el-input v-model="currentProduct.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="currentProduct.productName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="currentProduct.stock" type="text"></el-input>
        </el-form-item>
         <el-form-item label="价格">
          <el-input v-model="currentProduct.price" type="text"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentProduct.status">
            <el-option label="禁用" :value="0"/>
            <el-option label="启用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>
    <!-- 创建 -->
    <el-dialog v-model="isAddOpen" title="添加" >
      <el-form :model="productForm" label-width="100px" style="width: 400px">
        <el-form-item label="名称">
          <el-input v-model="productForm.productName"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="productForm.stock "  type="text"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="productForm.price " ></el-input>
        </el-form-item>
        <!-- 分类下拉 -->
      <el-form-item label="产品分类" prop="categoryId">
        <el-select v-model="productForm.categoryId" placeholder="请选择分类" clearable>
          <el-option  v-for="c in categoryList"  :key="c.id"  :label="c.categoryName"  :value="c.id"/>
        </el-select>
      </el-form-item>
      <!-- 供应商下拉 -->
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="productForm.supplierId" placeholder="请选择供应商" clearable>
          <el-option v-for="s in supplierList" :key="s.id" :label="s.supplierName" :value="s.id"/>
        </el-select>
      </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isAddOpen = false">取消</el-button>
        <el-button type="primary" @click="addProduct">保存</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  display: flex; /* 开启Flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.userList-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}
.btn{
  display: flex;
  gap: 2px;
}
.pagination-container {
  // padding: 10px 0;
  align-items: center;
}

/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width: calc(100% - 30px); /* 宽度与搜索框一致 */
  margin-left: 35px; /* 左侧外边距15px，与搜索框padding-left匹配 */
  margin-top: 40px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */

}
.title-link {
  color: #409eff; /* 蓝色，模拟链接样式 */
  cursor: pointer;
  text-decoration: underline; /* 下划线，增强可点击提示 */
}

</style>

